package com.lianqi.emcpframework.design.domain.event;

import javafx.concurrent.Task;
import lombok.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program emcp-framework
 * @ClassName DomainEventExecutor
 * @description: 领域事件执行器定义
 * @author: sky
 * @create: 2019/06/06 10:11
 */
public interface DomainEventExecutor {
    Logger LOGGER = LoggerFactory.getLogger(DomainEventExecutor.class);

    default <E extends DomainEvent> void submit(DomainEventHandler<E> handler,E event){
        submit(new Task<>(handler,event));
    }

    <E extends DomainEvent> void submit(Task<E> task);

    @Value
    class  Task<E extends DomainEvent> implements Runnable{
        private final DomainEventHandler<E> handler;
        private final E event;

        @Override
        public void run() {
            try {
                this.handler.handle(this.event);
            }catch (Exception e){
                LOGGER.error("failed to handle event {} use {}",this.event,this.handler,e);
            }
        }
    }

    /**
     * 同步执行线程
     */
    class SyncExecutor implements DomainEventExecutor{

        @Override
        public <E extends DomainEvent> void submit(Task<E> task) {
            task.run();
        }
    }

}
